from socketserver import BaseRequestHandler, ThreadingTCPServer
from app import app
from flask_sqlalchemy import SQLAlchemy
from models import GroupOfPeople, Camera
from exts import get_time

# app.app_context().push()
db = SQLAlchemy(app)


class Handler(BaseRequestHandler):

    def handle(self) -> None:
        address, pid = self.client_address
        print(f'{address} connected!')
        while True:
            data = self.request.recv(1024)
            if len(data) <= 0:
                print("close!")
                break

            print(f'receive data: {data.decode()}')
            data_dict = eval(data.decode())
            # 存入数据库
            camera = db.session.query(Camera).filter(Camera.ipv4 == data_dict.get("ip")).first()
            if camera is None:
                camera = Camera(ipv4=data_dict.get("ip"),
                                place="未知",
                                state="未加入系统中的摄像头")

            gop = GroupOfPeople(time=get_time(),
                                mask=data_dict.get("mask"),
                                no_mask=data_dict.get("no_mask"),
                                camera=camera)
            db.session.add(gop)
            db.session.commit()


if __name__ == '__main__':
    server = ThreadingTCPServer(('0.0.0.0', 5001), Handler)
    print("Listening")
    server.serve_forever()
